package org.zjvis.datascience.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zjvis.datascience.common.dto.PluginDTO;
import org.zjvis.datascience.common.util.Page;
import org.zjvis.datascience.common.vo.PluginQueryVO;
import org.zjvis.datascience.common.vo.PluginVO;
import org.zjvis.datascience.service.mapper.PluginMapper;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class PluginService {
    @Autowired
    private PluginMapper pluginMapper;

    public boolean save(PluginDTO plugin) {
        return pluginMapper.save(plugin);
    }

    public boolean update(PluginDTO plugin) {
        return pluginMapper.update(plugin);
    }

    public void delete(Long id) {
        pluginMapper.delete(id);
    }

    public List<PluginDTO> queryByStatus() {
        return pluginMapper.queryByStatus();
    }

    public PluginDTO queryByName(String name){
        return pluginMapper.queryByName(name);
    }

    public List<PluginDTO> queryAll() {
        return pluginMapper.queryAll();
    }

    public PluginDTO queryById(Long id){
        return pluginMapper.queryById(id);
    }

    public PluginDTO queryByToken(String token){
        return pluginMapper.queryByToken(token);
    }

    public Page<PluginVO> queryByCondition(PluginQueryVO vo) {
        String search = vo.getSearch();
        if (StringUtils.isNotEmpty(search)) {
            search = "%" + search + "%";
        } else {
            search = null;
        }
        vo.setSearch(search);
        Integer curPage = vo.getCurPage();
        Integer pageSize = vo.getPageSize();
        Integer offset;
        if (curPage != null && pageSize != null) {
            offset = (curPage - 1) * pageSize;
            vo.setOffset(offset);
        }
        List<PluginDTO> data = pluginMapper.queryByCondition(vo);
        Integer totalCount = pluginMapper.queryTotolCount(vo);
        List<PluginVO> views = data.stream().map(PluginDTO::view).collect(Collectors.toList());
        Page<PluginVO> page = new Page<>();
        page.setCurPage(curPage);
        page.setPageSize(pageSize);
        page.setTotalElementsAndPage(totalCount);
        page.setData(views);
        return page;
    }
}
